import React, {Component} from "react";
import {Link} from "react-router";
import {Table, Tree, Button, Form, Input, Popconfirm, Tooltip, DatePicker, Modal, Row, Col, Icon, message} from "antd";
import FuncForm from "./funcform";
import auth from "../../common/auth";
const confirm = Modal.confirm;
const TreeNode = Tree.TreeNode;
const FormItem = Form.Item;
const RangePicker = DatePicker.RangePicker;


let columns = [
    {
        title: '菜单名称',
        dataIndex: 'funcname'
    }, {
        title: 'URL',
        dataIndex: 'url'
    }, {
        title: '是否用于菜单',
        dataIndex: 'ismenu',
        render: (text, record, index)=> {
            switch (text) {
                case 1:
                    return <span className="green">是</span>;
                    break;
                case 0:
                    return <span className="gray">否</span>;
                    break;
            }
        }
    }, {
        title: '修改人',
        dataIndex: 'modifyuser'
    }, {
        title: '修改日期',
        dataIndex: 'modifytime'
    }, {
        title: '描述',
        dataIndex: 'described'
    }
];

export default class FuncList extends Component {
    state = {
        selectedKeys: [],
        selectedRowKeys: [],
        pagination: false,
        autoExpandParent: true,
        record: {},
        modalVisible: false,
        title: '',
        option: '',
        params: {},
        startDate: null,
        endDate: null,
        cname: '',
        funcData: {}
    }

    handelOnRowClick(record, index) {
        console.log(record);
         this.setState({
           selectedRowKeys:[record.id],
           selectedRows:[record],
           record
         });
    }

    onSelectChange(selectedRowKeys) { //已选择行的key
        this.setState({selectedRowKeys});
    }

    onSelectdTable(record, selected, selectedRows) { //当前选择的行
       // console.log(record);
        if(selectedRows.length>0){
            this.setState({
                record,
                selected,
                selectedRows
            });
        }
    }

    handleChangeDate(date) {
        if (date.length > 0) {
            this.setState({
                startDate: date[0],
                endDate: date[1]
            });
        }
    }

    handleChangeKeyword(e) {
        this.setState({
            cname: e.target.value
        })
    }

    /**
     * 表格表单查询
     * @return {[type]} [description]
     */
    handelBtnQuery() {
        let params = this.state.params;
        if (this.state.startDate != null) {
            params.startDate = this.state.startDate;
        } else {
            delete params.startDate;
        }
        if (this.state.endDate != null) {
            params.endDate = this.state.endDate;
        } else {
            delete params.endDate;
        }
        if (this.state.cname != null && this.state.cname != "") {
            params.cname = this.state.cname;
        } else {
            delete params.cname;
        }
        console.log(params);
        this.fetch(params);
    }

    /**
     * 添加数据
     * @return {[type]} [description]
     */
    onAddArticle() {
        this.fetchParentFunc();
        this.setState({
            modalVisible: true,
            title: '添加菜单信息',
            record: {},
            option: 'add',
        });
    }

    /**
     * 修改数据
     * @return {[type]} [description]
     */
    handleBtnEdit() {
        if (this.state.selectedRows.length == 1) {
            this.fetchParentFunc();                         
            this.setState({
                modalVisible: true,
                title: "编辑菜单信息",
                option: 'update'
            });
            this.refs.func_form.getForm().resetFields();
        } else {
            message.info("只能修改一条数据！");
        }
    }

    /**
     * 删除数据
     * @return {[type]} [description]
     */
    handleBtnDelete() {
        let keyId = this.state.selectedRowKeys.join(",");
        let t = this
        confirm({
            title: '删除确认',
            content: '数据删除后无法恢复，确认要删除吗？',
            confirmLoading: this.state.delLoading,
            onOk(){
                t.setState({delLoading: true});
                let params = {
                    id: keyId
                };
                auth.fetch("/sys/func/delete", params, function (result) {
                    this.setState({delLoading: true});
                    if (result.result == '0') {
                        message.success(result.message);
                        this.fetch();
                    } else {
                        message.error(result.message, 10);
                    }
                }.bind(t));
            },
            onCancel() {
            }
        });
    }

    handleBtnView() {
        if (this.state.selectedRows.length == 1) {
            this.fetchParentFunc();
            this.setState({
                modalVisible: true,
                title: "查看菜单信息",
                option: 'view'
            });
        } else {
            message.info("只能修改一条数据！");
        }
    }

    /**
     * 保存数据
     * @return {[type]} [description]
     */
    handleOk() {
        //this.refs.article_form.handleSubmit();
        if (this.state.option == "view") {
            this.setState({
                modalVisible: false
            });
            return;
        }
        let myForm = this.refs.func_form;//.getForm();
        myForm.validateFields((errors, values) => {
            if (!!errors) {
                ('Errors in form!!!');
                return;
            }
            let form_value = myForm.getFieldsValue();
            let url = "/sys/func/save";
            if (this.state.option == "update") {
                url = "/sys/func/update";
            }
            auth.fetch(url, form_value, function (data) {
                this.setState({loading: false});
                if (data.result == '1') {
                    message.error(data.message, 10);
                    myForm.getForm().resetFields();
                } else {
                    message.success(data.message, 10);
                    this.setState({modalVisible: false});
                    myForm.getForm().resetFields();
                    //加载表格数据
                    this.fetch(this.state.params);
                }
            }.bind(this));
        });
    }

    fetch(params = {}) {
        this.setState({loading: true, params: params});
        auth.fetch('/sys/func/findlistTreeByWhere', params, (res) => {
            if (res.result == "0") {
                this.setState({
                    loading: false,
                    tableData: res.data
                });
            } else {
                message.error(res.msg, 10);
            }
        });
    }

    handleCancel() {
        this.setState({modalVisible: false});
        this.refs.func_form.getForm().resetFields();
    }

    handelEditModal(record, operate) {

        let title = "新增菜单信息";
        if (operate == "update") {
            title = "编辑菜单信息";
        } else if (operate == "view") {
            title = "查看菜单信息";
        }
        this.fetchParentFunc();
        this.setState({modalVisible: true, title: title, record: record, option: operate});
    }

     fetchParentFunc() {
        auth.fetch('/sys/func/findlistByWhere', {parentid: 0}, (res) => {
            if (res.result == "0") {
                this.setState({
                    formfuncData: res.data
                });
            } else {
                message.error(res.msg, 10);
            }
        });
    }

    deleteFn(params = {}) {
        auth.fetch("/sys/func/delete", params, function (result) {
            this.setState({delLoading: true});
            if (result.result == '0') {
                message.success(result.message);
                this.fetch();
            } else {
                message.error(result.message, 10);
            }
        }.bind(this));
    }

    expandedRowRender(e) {
        console.log(e);
    }

    componentDidMount() { //初始化
       
        this.fetch();
    }

    render() {
        const {selectedRowKeys} = this.state;
        const rowSelection = {
            selectedRowKeys,
            onSelect: this.onSelectdTable.bind(this),
            onChange: this.onSelectChange.bind(this),
        };
        let btn_disabled = selectedRowKeys.length > 0 ? false : true;
        return (
            <div>
                <div className="form-query">
                    <Form inline>
                        <FormItem label="菜单名称">
                            <Input placeholder="请输入搜索的菜单名称" ref="cname" size="default"
                                   onChange={this.handleChangeKeyword.bind(this)}/>
                        </FormItem>
                        <Button type="primary" onClick={this.handelBtnQuery.bind(this)}>查询</Button>
                    </Form>
                </div>
                <div style={{marginTop: 10}}>
                    <Button type="primary" className="btn-divider" onClick={this.onAddArticle.bind(this)}>新建</Button>
                    <Button type="primary" className="btn-divider" disabled={btn_disabled}
                            onClick={this.handleBtnEdit.bind(this)}>编辑</Button>
                    <Button type="primary" className="btn-divider" disabled={btn_disabled}
                            onClick={this.handleBtnView.bind(this)}>查看</Button>
                    <Button type="primary" className="btn-divider" disabled={btn_disabled}
                            onClick={this.handleBtnDelete.bind(this)}>删除</Button>
                </div>
                <Table columns={columns} defaultExpandedRowKeys={[1]} rowKey={record => record.id}
                       rowSelection={rowSelection} dataSource={this.state.tableData}
                       pagination={this.state.pagination} loading={this.state.loading}
                       onRowClick={this.handelOnRowClick.bind(this)}/>

                <Modal wrapClassName="vertical-center-modal" visible={this.state.modalVisible} width={600}
                       maskClosable={false} title={this.state.title} onOk={this.handleOk.bind(this)}
                       onCancel={this.handleCancel.bind(this)}>
                    <div className="modal_from">
                        <FuncForm ref="func_form" init={{option: this.state.option, recorddata: this.state.record,formfuncData:this.state.formfuncData}}/>
                    </div>
                </Modal>

            </div>
        );
    }
};
